package net.alche.al.util.alches;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ToolRegex
 */
public class ToolRegex {
  /**
   * 获取"宏"参数 以"{XX}"的内容
   * 
   * @param txt 文本
   * @return
   */
  public List<String> getMacroList(String txt) {
    List<String> list = matchers("\\{(\\w|:|-|@)+\\}", txt);
    if (list != null && !list.isEmpty()) {
      for (int i = 0; i < list.size(); i++) {
        String str = list.get(i);
        list.set(i, str.substring(1, str.length() - 1));
      }
    }
    return list;
  }

  /**
   * 正则表达式匹配
   * 
   * @param reg 正则表达式
   * @param txt 被检查的文本内容
   * @return
   */
  public List<String> matchers(String reg, String txt) {
    Pattern pat = Pattern.compile(reg);
    Matcher mat = pat.matcher(txt);
    List<String> list = new ArrayList<>();
    while (mat.find()) {
      list.add(mat.group());
    }
    return list;
  }

  public String matcher(String reg, String txt) {
    Pattern pat = Pattern.compile(reg);
    Matcher mat = pat.matcher(txt);
    while (mat.find()) {
      return mat.group();
    }
    return "";
  }

  /**
   * 测试txt是否符合reg的规则
   * @param reg
   * @param txt
   * @return
   */
  public boolean test(String reg, String txt) {
    Pattern pat = Pattern.compile(reg);
    Matcher mat = pat.matcher(txt);
    return mat.matches();
  }

  public String matcher(String start, String end, String txt) {
    return matcher("(?<=" + start + ")((\n|\r|\r\n|.)+?)(?=" + end + ")", txt);
  }
}